import * as React from 'react';
import { Form, Input } from 'antd';
import CustomModal from 'components/common/CustomModal';

const FormItem = Form.Item;

function parseFileName(fileName: string) {
  let idx = fileName.lastIndexOf('.');

  if (idx === -1) {
    idx = fileName.length;
  }

  return {
    name: fileName.slice(0, idx),
    ext: fileName.slice(idx),
  };
}

interface RenameProps {
  form: any;
  onOk: (name: string) => any;
  onCancel: () => any;
  name: string;
}

class Rename extends React.Component<RenameProps> {
  handleOk = () => {
    const { onOk, name, form } = this.props;
    const { ext } = parseFileName(name);

    form.validateFields((error: any, values: any) => {
      if (!error) {
        onOk(values.name + ext);
      }
    });
  };

  componentDidMount() {
    const { form, name } = this.props;

    form.setFieldsValue({
      name: parseFileName(name).name,
    });
  }

  render() {
    const { onCancel } = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };

    return (
      <CustomModal title="修改名称" width={500} onOk={this.handleOk} onCancel={onCancel}>
        <Form>
          <FormItem {...formItemLayout} label="name">
            {getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: '名称是必填项',
                },
              ],
            })(<Input />)}
          </FormItem>
        </Form>
      </CustomModal>
    );
  }
}

export default Form.create()(Rename);
